<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Services\Tools\CommonService;
use Illuminate\Http\Request;    //引用http请求类
use App\Exceptions\BasicException;  //引入框架异常处理类
use Illuminate\Support\Facades\Hash;    //引入hash
use App\Services\Cache\AdminCacheService;   //admin缓存
use App\Services\Tools\JwtService;    //引入JWT服务
use App\Services\Tools\FileService;   //引入文件处理类
use App\Response\Response;
use Illuminate\Support\Facades\Redis;
use Monolog\Handler\IFTTTHandler;

class IpLimitController extends BaseController
{
    /**
     * @api {post} /limit/set_switch IP限制开关设置
     * @apiVersion 0.1.0
     * @apiName IP限制开关设置
     * @apiGroup IP限制管理
     * @apiParam {number} switch  1 开启 2 关闭，必传
     * @apiSuccessExample 成功响应
     *{"code":200,"data":true}
     */
    public function setSwitch(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'switch'=>'required|in:1,2',
            ]
        );
        if($v->fails()) throw new BasicException(10001);
        $switch = $request->input('switch');
        $is_have_switch = app('repo_config')->queryConfig('IP_LIMIT_SWITCH');
        if ($is_have_switch){
            $where[] =['key','IP_LIMIT_SWITCH'];
            app('repo_config')->saveConfig($where,['value'=>$switch]);
        }else{
            $param =[
                'value'=>$switch,
                'key'=>'IP_LIMIT_SWITCH',
                'name'=>'ip限制的开关',
            ];
            app('repo_config')->addConfig($param);
        }
        Redis::del('DB_CONFIG_DATA');
        return Response::sendData(true);
    }

    /**
     * @api {post} /limit/set_login_switch IP限制登录开关设置
     * @apiVersion 0.1.1
     * @apiName IP限制登录开关设置
     * @apiGroup IP限制管理
     * @apiParam {number} switch  1 开启 2 关闭，必传
     * @apiSuccessExample 成功响应
     *{"code":200,"data":true}
     */
    public function set_login_switch(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'switch'=>'required|in:1,2',
            ]
        );
        if($v->fails()) throw new BasicException(10001);
        $switch = $request->input('switch');
        $is_have_switch = app('repo_config')->queryConfig('IP_LOGIN_LIMIT_SWITCH');
        if ($is_have_switch){
            $where[] =['key','IP_LOGIN_LIMIT_SWITCH'];
            app('repo_config')->saveConfig($where,['value'=>$switch]);
        }else{
            $param =[
                'value'=>$switch,
                'key'=>'IP_LOGIN_LIMIT_SWITCH',
                'name'=>'ip登录限制的开关',
            ];
            app('repo_config')->addConfig($param);
        }

        Redis::del('DB_CONFIG_DATA');
        return Response::sendData(true);
    }

    /**
     * @api {post} /limit/switch_status   获取开关限制状态
     * @apiVersion 0.1.0
     * @apiName 获取开关限制状态
     * @apiGroup IP限制管理
     * @apiSuccessExample 成功响应
     *{"code":200,"data":{"status(1已开启 2已关闭)":"2"}}
     */
    public  function switch_status(){
        $switch = app('repo_config')->queryConfig('IP_LIMIT_SWITCH');
        $status  = $switch->value;
        return  Response::sendData(['status'=>$status]);
    }


    /**
     * @api {post} /limit/login_switch_status   获取限制登录开关记录
     * @apiVersion 0.1.1
     * @apiName 获取限制登录开关记录
     * @apiGroup IP限制管理
     * @apiSuccessExample 成功响应
     *{"code":200,"data":{"status(1已开启 2已关闭)":"2"}}
     */
    public  function login_switch_status(){
        $switch = app('repo_config')->queryConfig('IP_LOGIN_LIMIT_SWITCH');
        $status  = $switch->value;
        return  Response::sendData(['status'=>$status]);
    }

    /**
     * @api {post} /limit/region_blacklist   添加地域黑名单
     * @apiVersion 0.1.0
     * @apiName 添加地域黑名单
     * @apiGroup IP限制管理
     * @apiParam {string} regions  地域名称（多个用逗号隔开，要带上单位：省、市），必传
     * @apiSuccessExample 成功响应
     *{"code":200,"data":true}
     */
    public  function  region_blacklist(Request $request){
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'regions'=>'required',
            ]
        );
        if($v->fails()) throw new BasicException(10001);
        $regions = $request->input('regions');
        $regions_arr = explode(',',$regions);
        $data =[];
        if ($regions_arr){
            foreach ($regions_arr as $value){
                $data[] =[
                    'type'=>1,
                    'region'=>$value,
                    'add_time'=>time(),
                ];
                Redis::sadd('ip:set_region_blacklist',$value);
            }
        }
        if ($data){
            app('repo_ip_limit')->add($data);
        }
        return Response::sendData(true);
    }

    /**
     * @api {post} /limit/login_region_blacklist   添加限制登录地域黑名单
     * @apiVersion 0.1.1
     * @apiName 添加限制登录地域黑名单
     * @apiGroup IP限制管理
     * @apiParam {string} regions  地域名称（多个用逗号隔开，要带上单位：省、市），必传
     * @apiSuccessExample 成功响应
     *{"code":200,"data":true}
     */
    public  function  login_region_blacklist(Request $request){
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'regions'=>'required',
            ]
        );
        if($v->fails()) throw new BasicException(10001);
        $regions = $request->input('regions');
        $regions_arr = explode(',',$regions);
        $data =[];
        if ($regions_arr){
            foreach ($regions_arr as $value){
                $data[] =[
                    'type'=>3,
                    'region'=>$value,
                    'add_time'=>time(),
                ];
                Redis::sadd('ip:login_set_region_blacklist',$value);
            }
        }
        if ($data){
            app('repo_ip_limit')->add($data);
        }
        return Response::sendData(true);
    }

    /**
     * @api {post} /limit/save_region   编辑地域黑名单
     * @apiVersion 0.1.0
     * @apiName 编辑地域黑名单
     * @apiGroup IP限制管理
     * @apiParam {string} regions  地域名称（多个用逗号隔开，要带上单位：省、市），必传
     * @apiSuccessExample 成功响应
     *{"code":200,"data":true}
     */
    public  function  save_region(Request $request){
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'regions'=>'required',
            ]
        );
        if($v->fails()) throw new BasicException(10001);
        app('repo_ip_limit')->del_regions();
        Redis::del('ip:set_region_blacklist');
        $regions = $request->input('regions');
        $regions_arr = explode(',',$regions);
        $data =[];
        if ($regions_arr){
            foreach ($regions_arr as $value){
                $data[] =[
                    'type'=>1,
                    'region'=>$value,
                    'add_time'=>time(),
                ];
                Redis::sadd('ip:set_region_blacklist',$value);
            }
        }
        if ($data){
            app('repo_ip_limit')->add($data);
        }
        return Response::sendData(true);
    }

    /**
     * @api {post} /limit/login_save_region   编辑限制登录地域黑名单
     * @apiVersion 0.1.1
     * @apiName 编辑限制登录地域黑名单
     * @apiGroup IP限制管理
     * @apiParam {string} regions  地域名称（多个用逗号隔开，要带上单位：省、市），必传
     * @apiSuccessExample 成功响应
     *{"code":200,"data":true}
     */
    public  function  login_save_region(Request $request){
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'regions'=>'required',
            ]
        );
        if($v->fails()) throw new BasicException(10001);
        app('repo_ip_limit')->login_del_regions();
        Redis::del('ip:login_set_region_blacklist');
        $regions = $request->input('regions');
        $regions_arr = explode(',',$regions);
        $data =[];
        if ($regions_arr){
            foreach ($regions_arr as $value){
                $data[] =[
                    'type'=>3,
                    'region'=>$value,
                    'add_time'=>time(),
                ];
                Redis::sadd('ip:login_set_region_blacklist',$value);
            }
        }
        if ($data){
            app('repo_ip_limit')->add($data);
        }
        return Response::sendData(true);
    }

    /**
     * @api {post} /limit/region_blacklist_data   地域黑名单数据
     * @apiVersion 0.1.0
     * @apiName 地域黑名单数据
     * @apiGroup IP限制管理
     * @apiSuccessExample 成功响应
        {
        "code": 200,
        "data": "上海市,杭州市,河北省,湖州市,北京市,河南省,南京市,重庆市"
        }
     */
      public   function  region_blacklist_data(){
           $regions =Redis::smembers('ip:set_region_blacklist');
           if ($regions){
               $regions = implode(',',$regions);
           }
           return Response::sendData($regions);
      }

    /**
     * @api {post} /limit/login_region_blacklist_data   限制登录地域黑名单数据
     * @apiVersion 0.1.1
     * @apiName 限制登录地域黑名单数据
     * @apiGroup IP限制管理
     * @apiSuccessExample 成功响应
        {
        "code": 200,
        "data": "上海市,杭州市,河北省,湖州市,北京市,河南省,南京市,重庆市"
        }
     */
    public   function  login_region_blacklist_data(){
        $regions =Redis::smembers('ip:login_set_region_blacklist');
        if ($regions){
            $regions = implode(',',$regions);
        }
        return Response::sendData($regions);
    }

    /**
     * @api {post} /limit/user_white_list   添加用户白名单
     * @apiVersion 0.1.0
     * @apiName 添加用户白名单
     * @apiGroup IP限制管理
     * @apiParam {number} user_code  用户编号（多个用逗号隔开），必传
     * @apiSuccessExample 成功响应
     *{"code":200,"data":true}
     */

    public  function  user_white_list(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'user_code'=>'required',
            ]
        );
        if($v->fails()) throw new BasicException(10001);
        $user_code = $request->input('user_code');
        $user_code_arr = explode(',',$user_code);
        if ($user_code_arr){
            //获取用户id
            $user_ids =app('repo_user_data')->getUserIds($user_code_arr);
            if ($user_ids){
                $data =[];
                if ($user_ids){
                    foreach ($user_ids as $key=>$value){
                        $data[] =[
                            'type'=>2,
                            'user_id'=>$value['user_id'],
                            'add_time'=>time(),
                        ];
                        Redis::sadd('ip:set_user_whitelist',$value['user_id']);
                    }
                }
                if ($data){
                    app('repo_ip_limit')->add($data);
                }
            }
        }
        return Response::sendData(true);
    }

    /**
     * @api {post} /limit/del_user_white   删除白名单
     * @apiVersion 0.1.0
     * @apiName 删除白名单
     * @apiGroup IP限制管理
     * @apiParam {number}   user_id，必传
     * @apiSuccessExample 成功响应
     *{"code":200,"data":true}
     */
    public   function  del_user_white(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'user_id'=>'required|numeric',
            ]
        );
        if($v->fails()) throw new BasicException(10001);
        $user_id = $request->input('user_id');
        Redis::srem('ip:set_user_whitelist',$user_id);
        app('repo_ip_limit')->del_user_white($user_id);
        return Response::sendData(true);
    }













    /**
     * @api {post} /limit/white_list   用户白名单列表
     * @apiVersion 0.1.0
     * @apiName 用户白名单列表
     * @apiGroup IP限制管理
     *  @apiParam {number} page   页数，非必传
     *  @apiParam {number} perPage   每页数量，非必传
     * @apiSuccessExample 成功响应
        {
            "code": 200,
            "data": {
                "list": [
                    {
                    "id(主键序号)": 15,
                    "user_id（用户id）": 547176,
                    "add_time（添加时间）": "2020-09-19 15:53:23",
                    "user_code（用户编号）": 999981,
                    "nickname（昵称）": "CK",
                    "head_picture（头像）": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/android_images/547176/20191112181028_1573553427997743.jpg"
                    }
                ],
                "meta": {
                    "page": 1,
                    "limit": 20,
                    "next": null,
                    "total": 6
                }
            }
        }
     */
    public  function  white_list(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'page'=>'filled|numeric',
                'perPage'=>'filled|numeric',
            ]
        );
        if($v->fails()) throw new BasicException(10001);
        $page = $request->input('page',1);
        $perPage = $request->input('perPage',20);

        $list =  app('repo_ip_limit')->white_list($page,$perPage);
          if ($list){
              foreach ($list as $key=>$value){
                  $value->add_time =date('Y-m-d H:i:s',$value->add_time);
                  if (isset($value->user_data->user_code)){
                      $value->user_code =$value->user_data->user_code;
                  }else{
                      $value->user_code ='';
                  }
                  if (isset($value->user_data->nickname)){
                      $value->nickname =$value->user_data->nickname;
                  }else{
                      $value->nickname ='';
                  }
                  if (isset($value->user_data->head_picture)){
                      $value->head_picture =$value->user_data->head_picture;
                  }else{
                      $value->head_picture ='';
                  }
                  unset($value->user_data);
              }
        }
        return Response::sendList($list);
    }

    /**
     * @api {post} /limit/record_channel_ip   记录渠道ip
     * @apiVersion 0.1.0
     * @apiName 记录渠道ip
     * @apiGroup IP限制管理
     * @apiParam {string} channel  渠道名称，非必传
     * @apiSuccessExample 成功响应
     *{"code":200,"data":true}
     */

    public   function  record_channel_ip(Request $request){

        $channel = $request->input('channel','channel');
        $ip = $request->ip();
        $today=strtotime(date('Y-m-d H:i:s',strtotime(date("Y-m-d"),time())));//今天零点
        $tomorrow =strtotime(date('Y-m-d H:i:s',$today+86400));//明天零点
        $ip = sprintf("%u",ip2long($ip));
        $channel_arr = CommonService::downloadChannel();
        if (in_array($channel,$channel_arr)){
            $channel_ids = array_keys($channel_arr,$channel);
            $channel_id=$channel_ids[0];
            $param = [$today,$tomorrow];
            $count = app('repo_channel_ip_number')->channelTotal($param,$ip);
            if ($count< 20){
                $data1 =[
                    'channel_id'=>$channel_id,
                    'ip'=>$ip,
                    'add_time'=>time(),
                ];
                app('repo_channel_ip_number')->add_channel_one($data1);
            }
        }else{
            $channel_id = 0;
        }

        $data2 =[
            'channel_id'=>$channel_id,
            'ip'=>$ip,
            'add_time'=>time(),
        ];
        app('repo_channel_ip_number')->add_channel_two($data2);
        return Response::sendData('https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/app/qpyy_1.10.8_218_2020-09-14_1108_jiagu_sign_1_xuanfuqiu_sign.apk');
    }









}
